
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    screenHeight: app.globalData.screenHeight,
    userInfo:{},
    
    searchParams:{
      pageNum: 1,
      pageSize: 6,
      keyword:'',
      pages:'',
      total:'',
      isPublishQuery:1
    },
    noData: true,
    orderList:{},
    onReachBottomLoading: false,
    orderStatus:{
      0:'待支付',
      1:'已支付(待查询)',
      2:'查询中',
      3:'报告已生成',
      4:'报告生成失败',
      5:'已退款',
      6:'退款成功',
      99:'超时关闭',
      98:'已取消',
      97:'购买报告错误',
      96:'查询报告错误'
    },
    reporType:{
      'c300InsuranceReport':'车300碰撞保险记录',
      'c300MtnceReport':'车300保养维修记录',
      'cbsInsuranceReport':'查博士碰撞保险记录',
      'cbsMtnceReport':'查博士保养维修记录'
    },
    searchtype:null,
    orderInfo:{
      orderNo:'',
      orderStatus: 0,
      payInfo:{}
    },
    scopeRow: {},
    scopePage: 1,
    scopeIndex: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.InitUserStatus();
  },
  // 检查一下登录状态。
  async InitUserStatus(options){
      app.showLoading("获取用户信息");
      await app.checkToken();
      this.InitUserInfo();
      wx.hideLoading();
  },
  InitUserInfo(){
      let userInfo = app.globalData.userInfo;
      // 这里再验证一遍权限。
      if (userInfo.roleList.indexOf('addCar') == -1) {
          app.showNoAuthOrNoGrant('您无权操作查看此页面');
          return;
      }else{
        this.goQuery();
      }
  },
  chooseReport(e) {
    let page = e.currentTarget.dataset.page;
    let index = e.currentTarget.dataset.idx;
    let item = this.data.orderList[page][index];
    app.globalData.scopeRowReport = item
    this.setData({
      'scopeRow': item,
      'scopePage': page,
      'scopeIndex': index
    });
  },
  bindtapInput(e){
    this.setData({
      'searchParams.keyword': e.detail.value
    })
  },
  // 查询车辆列表。
  goQuery(e){
    if(undefined  != e && this.data.searchtype != 1){
      if(this.data.searchParams.keyword == ''){
        return;
      }
    }
    let searchtype = undefined ==  e?0:e.currentTarget.dataset.searchtype
    this.setData({
      'searchParams.pageNum':1,
      'searchParams.total':'',
      'searchParams.pages':'',
      'orderList': {},
      'searchtype': searchtype
    });
    this.reportOrderList(this.data.searchParams);
  },
  clearQuery(){
    this.setData({
      'searchParams.keyword': '',
      'searchtype': 0
    });
    this.goQuery();
  },
  reportOrderList(searchParams){
    this.setData({
        'onReachBottomLoading': true
    })
    app.sHttp.reportOrderList(searchParams).then(res=>{
      let orderList = this.data.orderList;
      orderList[searchParams.pageNum] = res.result.reportOrderList;
      if (0 == res.result.total) {
        this.setData({
          'noData': true,
          'onReachBottomLoading': false
        })
      }else{
        this.setData({
          'noData': false,
          'orderList': orderList,
          'searchParams.total':res.result.total,
          'searchParams.pages': res.result.pages,
          'onReachBottomLoading': false
        });
      }
    },err=>{
      app.error(err.msg);
      this.setData({
        'onReachBottomLoading': false
      })
    })
  },
  onReachBottom(){
    if (this.data.searchParams.pageNum == this.data.searchParams.pages) {
        //app.alert('没有更多了哦~');
    }else{
        let self = this;
        this.setData({
            'searchParams.pageNum': self.data.searchParams.pageNum+1
        });
        this.reportOrderList(this.data.searchParams);
    }
  },
  copyText: function (e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },
  lookReprotInfo(e){
    app.globalData.lookReportInfoUrl = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: '/pages/carQueryRecord/detailed/detailed',
    })
  },
  // 拉起重新支付。
  reportOrderPayInfo(e){
    let self = this;
    let orderNo = e.currentTarget.dataset.orderno;
    app.sHttp.reportOrderPayInfo(orderNo).then(res=>{
      this.setData({
        'orderInfo.payInfo': res.payInfo,
        'orderInfo.orderNo': orderNo,
      }, () => {
        self.tuneUpPay();
      });
    },err=>{
      app.error(err.msg);
    })
  },
  reportOrderCancel(e){
    let self = this;
    wx.showModal({
      title: '提示',
      content: '您确定要取消当前订单',
      success (res) {
        if (res.confirm) {
          let orderNo = e.currentTarget.dataset.orderno;
          app.sHttp.reportOrderCancel(orderNo).then(res=>{
            app.alert('取消成功,已退还余额与积分');
            let that = self;
            setTimeout(() => {
              that.goQuery();
            }, 1500);
          },err=>{
            app.error(err.msg);
          })

        }
      }
    })
  },
  tuneUpPay(){
    // 从Data里面拿参数
    let orderInfo = this.data.orderInfo;
    try {
      if ('' == orderInfo.orderNo || undefined == orderInfo.payInfo.paySign) {
        app.alert('支付参数不完整');
        return;
      };
      // 吊起支付。
      let self = this;
      wx.requestPayment({
          timeStamp: orderInfo.payInfo.timeStamp,
          nonceStr: orderInfo.payInfo.nonceStr,
          package: orderInfo.payInfo.package,
          signType: orderInfo.payInfo.signType,
          paySign: orderInfo.payInfo.paySign,
          success (res) {
              // 查询订单完成信息。
              let _this = self;
              app.showLoading('查询订单状态');
              setTimeout(() => {
                  wx.hideLoading();
                  _this.OrderPayResult();
              }, 5000);
          },
          fail (res) {
            self.payOk('支付失败','您已取消支付，可在订单列表中选择继续支付');
          }
      })
    } catch (error) {
      app.alert('支付参数不完整');
    }
  },
  OrderPayResult(){
      let orderInfo = this.data.orderInfo;
      if ('' == orderInfo.orderNo) {
          app.alert('支付参数不完整');
          return;
      };
      app.sHttp.reportOrderPayResult(orderInfo.orderNo).then(res =>{
          let orderStatus = res.orderStatus;
          if (0 == orderStatus) {
              this.payOk('查询结果','请等待几分钟后在订单列表中查看订单状态，如长时间未显示成功状态，请联系客服处理');
              return;
          }else if (1 == orderStatus) {
              this.payOk('提交完成','您当前订单提交完成，请等待报告结果');
              return;
          }else{
            this.payOk('查询结果','请等待几分钟后刷新查看，如长时间未显示成功状态，请联系客服处理');
          }
      },err=>{
        app.error(err.msg);
      })
  },
  payOk(title,content){
    let self = this;
    wx.showModal({
      title: title,
      content: content,
      confirmText: '我知道了',
      showCancel: false,
      success(res) {
          self.goQuery();
      }
    })
  },
  BackPage() {
    var that = this;
    wx.navigateBack({
      delta: 1,
      fail: function () {
        that.toHome();
      }
    });
  },
  toHome() {
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },

})